<template>
  <Card v-show="shuax">
    <div class="flexCSB">
      <Button type="primary" @click="addAccount">添加角色</Button>
      <div style="display: flex">
        <Input
          placeholder="请输入角色名"
          suffix="ios-search"
          style="width: 300px; margin-left: 10px"
          v-model="name"
          @on-change="change"
        ></Input>
      </div>
    </div>

    <Table
      class="table"
      :loading="loading1"
      @on-row-dblclick="onRowDblclick"
      highlight-row
      :columns="columns"
      :data="data"
    ></Table>
    <Page
      class="page"
      show-total
      :total="total"
      :current.sync="current"
      show-elevator
      @on-change="changePage"
    />

    <Modal title="修改角色" v-model="jurisdictionModal" width="650">
      <Form ref="form" :model="createData" class="form" :label-width="120">
        <FormItem label="角色名称：" prop="name">
          <Input v-model="createData.name" clearable />
        </FormItem>
        <FormItem label="备注：" prop="remark">
          <Input v-model="createData.remark" clearable />
        </FormItem>
        <FormItem label="组织机构">
          <Select v-model="createData.organizationId">
            <Option
              v-for="(item, index) in orgList"
              :key="index"
              :value="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="系统管理权限：">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            node-key="idx"
            :default-expand-all="true"
            show-checkbox
            @check="changeTree"
            :default-checked-keys="defaultKeys"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <RadioGroup
                  v-model="data.permissions"
                  type="button"
                  size="small"
                  v-if="data.isEdit"
                >
                  <Radio :label="data.p1">查看</Radio>
                  <Radio :label="data.p2">查看&编辑</Radio>
                  <Radio :label="data.p3">查看&删除</Radio>
                  <Radio :label="data.p4">全部</Radio>
                  <Radio label>无权限</Radio>
                </RadioGroup>
              </span>
            </span>
          </el-tree>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          class="Button"
          type="primary"
          @click="submit2"
          :loading="loading4"
          >确认修改</Button
        >
      </div>
    </Modal>

    <Modal v-model="addAccountModal" title="新增角色" width="650">
      <Form ref="form" :model="createData" class="form" :label-width="120">
        <FormItem label="角色名称：" prop="name">
          <Input
            v-model="createData.name"
            placeholder="请输入角色名称"
            clearable
          />
        </FormItem>

        <FormItem label="备注：" prop="remark">
          <Input
            v-model="createData.remark"
            placeholder="请输入角色备注"
            clearable
          />
        </FormItem>
        <FormItem label="组织机构">
          <Select v-model="createData.organizationId">
            <Option
              v-for="(item, index) in orgList"
              :key="index"
              :value="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="系统管理权限：">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            @check="changeTree"
            show-checkbox
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <RadioGroup
                  v-model="data.permissions"
                  type="button"
                  size="small"
                  v-if="data.isEdit"
                >
                  <Radio :label="data.p1">查看</Radio>
                  <Radio :label="data.p2">查看&编辑</Radio>
                  <Radio :label="data.p3">查看&删除</Radio>
                  <Radio :label="data.p4">全部</Radio>
                  <Radio label="">无权限</Radio>
                </RadioGroup>
              </span>
            </span>
          </el-tree>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          class="Button"
          type="primary"
          @click="create"
          :loading="loading5"
          >确认新增</Button
        >
      </div>
    </Modal>
    <Modal
      title="权限详情"
      v-model="perModal"
      width="65"
      :closable="false"
      :mask-closable="true"
    >
      <div class="perView">
        <div class="perBox" v-for="(item, index) in perList" :key="index">
          {{
            item.menuName +
            item.permission.slice(
              item.permission.lastIndexOf(":"),
              item.permission.length
            )
          }}
        </div>
      </div>
    </Modal>
  </Card>
</template>

<script>
import { md5 } from "../../config/md5.js";
// 现在我要把obj字面量创建里的属性深拷贝（ 属性值是引用类型也要深拷贝 ）
function deepClone(source) {
  const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
  for (let keys in source) {
    // 遍历目标
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === "object") {
        // 如果值是对象，就递归一下
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = deepClone(source[keys]);
      } else {
        // 如果不是，就直接赋值
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
}
export default {
  inject: ["reload"],
  data() {
    return {
      name: "",
      modalDetail: false,
      detailData: {},
      detailDataID: "",
      loading1: false,
      // loading3: false,
      loading4: false,
      loading5: false,
      delId: "",
      id: "",
      shuax: true,
      columns: [
        { title: "角色名称", key: "name", align: "center", minWidth: 120 },
        { title: "备注", key: "remark", align: "center", minWidth: 200 },
        { title: "创建时间", key: "gmtCreate", align: "center", minWidth: 200 },
        {
          title: "角色权限",
          align: "center",
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  on: {
                    click: () => {
                      this.openModel(params.row);
                    },
                  },
                },
                "查看"
              ),
            ]);
          },
        },
        {
          title: "操作",
          align: "center",
          width: 300,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    // loading: this.loading3,
                  },
                  on: {
                    click: () => {
                      this.jurisdiction(params);
                    },
                  },
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                  },
                  style: {
                    marginLeft: "10px",
                  },
                  on: {
                    click: () => {
                      this.delete(params);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      data: [],
      current: 1,
      size: 10,
      states: "0",
      total: 0,

      jurisdictionModal: false,
      menuId: "",

      addAccountModal: false,
      createData: {
        name: "",
        remark: "",
        permissions: [],
        organizationId: "",
      },
      treeData: [],
      orgList: [],
      defaultProps: {
        children: "leaf",
        label: "label",
      },
      permissions: [],

      perModal: false,
      perList: [],
      defaultKeys: [],
    };
  },
  // 开始请求接口
  created() {
    this.getRoleData();
    this.getGroupSelector();
  },
  // 方法列表
  methods: {
    addAccount() {
      this.getGroupSelector(); //组织结构
      this.createData = {
        name: "",
        remark: "",
        permissions: [],
        organizationId: "",
      };

      // 权限选择器
      this.$http("/chongqing/stage/role/treeSelector", {}, "get", (res) => {
        if (res.data.code === 1000) {
          // this.treeData = this.getMenusPermissions(res.data.data);
          this.treeData = [];
          let list = res.data.data;
          list.map((item) => {
            let obj = item;
            if (obj.leaf.length > 0) {
              for (let i in obj.leaf) {
                if (obj.leaf[i].stringPermission) {
                  obj.leaf[i].label =
                    obj.leaf[i].menuName +
                    obj.leaf[i].stringPermission.slice(
                      obj.leaf[i].stringPermission.lastIndexOf(":"),
                      obj.leaf[i].stringPermission.length
                    );
                } else {
                  obj.leaf[i].label = obj.leaf[i].menuName;
                }
              }
            }
            if (obj.stringPermission) {
              obj.label =
                obj.menuName +
                obj.stringPermission.slice(
                  obj.stringPermission.lastIndexOf(":"),
                  obj.stringPermission.length
                );
            } else {
              obj.label = obj.menuName;
            }
            this.treeData.push(obj);
          });
          console.log(this.treeData);
          this.addAccountModal = true;
        } else {
          this.$Message.error(res.data.msg);
        }
      });
    },
    getGroupSelector() {
      // 组织机构选择器
      this.$http("/chongqing/stage/group/selector", {}, "get", (res) => {
        if (res.data.code === 1000) {
          this.orgList = res.data.data;
          console.log(this.orgList);
        } else {
          this.$Message.error(res.data.msg);
        }
      });
    },
    // 传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象，包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
    changeTree(row, params) {
      console.log(row, params);
      let arr1 = [];
      let arr2 = [];
      params.checkedNodes.map((item) => {
        arr1.push({
          id: item.id,
          menuName: item.menuName,
          parentId: item.parentId,
          permission: item.stringPermission,
        });
      });
      params.halfCheckedNodes.map((item) => {
        arr2.push({
          id: item.id,
          menuName: item.menuName,
          parentId: item.parentId,
          permission: item.stringPermission,
        });
      });
      console.log(arr1, arr2);
      this.permissions = arr1.concat(arr2);
      console.log(this.permissions);
    },
    delete(params) {
      let delId = params.row.id;
      console.log(delId);
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http(
            "/chongqing/stage/account/deleteAccount",
            {
              roleId: delId,
            },
            "post",
            (res) => {
              console.log(res);
              if (res.data.code == 1000) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                // this.reload();
                this.current = 1;
                this.getRoleData();
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //
    openModel(row) {
      console.log(row.permissions);
      let plist = row.permissions;
      this.perList = [];
      plist.map((item) => {
        let arr = item.permission.split(",");
        arr.map((it) => {
          this.perList.push({
            id: item.id,
            menuName: item.menuName,
            parentId: item.parentId,
            permission: it,
          });
        });
      });
      console.log(this.perList);
      this.perModal = true;
    },
    // 角色列表
    getRoleData() {
      this.loading1 = true;
      this.$http(
        "/chongqing/stage/role/getRoleList",
        {
          current: this.current,
          name: this.name,
          size: this.size,
        },
        "post",
        (res) => {
          if (res.data.code == 1000) {
            console.log(res.data.data.records);
            this.data = res.data.data.records;
            this.total = res.data.data.total;
            // this.data.unshift({name:'超级管理员',id:'0'})
            // this.getRoleData();
          } else {
            this.$Message.error(res.data.msg);
          }
          this.loading1 = false;
        }
      );
    },
    getMenusPermissions(list) {
      console.log(list);
      // return arr;
    },

    // 新增接口
    create() {
      this.loading5 = true;

      // 查找重复元素
      let arrId = this.permissions.map((item) => item.id);
      const setter = new Set();
      const temp = new Set();
      for (const item of arrId) {
        if (setter.has(item)) {
          temp.add(item);
        } else {
          setter.add(item);
        }
      }
      // console.log(temp); // 有重复元素的id
      console.log(setter);
      let arr = Array.from(setter);
      let newArr = [];
      arr.map((it) => {
        let obj = {
          id: "",
          menuName: "",
          parentId: "",
          permission: "",
        };
        let arrP = [];
        this.permissions.map((item) => {
          if (item.id == it) {
            obj.id = item.id;
            obj.menuName = item.menuName;
            obj.parentId = item.parentId;
            arrP.push(item.permission);
          }
        });
        console.log(arrP);
        obj.permission = arrP.join(",");
        if (obj.permission) {
          newArr.push(obj);
        }
      });
      console.log(newArr);
      this.$http(
        "/chongqing/stage/role/addRole",
        {
          name: this.createData.name,
          remark: this.createData.name,
          permissions: newArr,
          organizationId: this.createData.organizationId,
        },
        "post",
        (res) => {
          if (res.data.code == 1000) {
            this.$Message.success("新增角色成功");
            this.addAccountModal = false;
            this.getRoleData();
          } else {
            this.$Message.error(res.data.msg);
          }
          this.loading5 = false;
        }
      );
    },
    // 修改
    async jurisdiction(params) {
      console.log(params.row);
      await this.getGroupSelector(); // 组织数据
      let { permissions, id } = deepClone(params.row);
      // this.loading3 = true;
      this.menuId = id;
      this.params = params;
      console.log(permissions);
      this.createData = {
        name: params.row.name,
        remark: params.row.remark,
        permissions: params.row.permissions,
        organizationId: params.row.organizationId,
      };
      let plist = params.row.permissions;
      this.permissions = [];
      plist.map((item) => {
        let arr = item.permission.split(",");
        arr.map((it) => {
          this.permissions.push({
            id: item.id,
            menuName: item.menuName,
            parentId: item.parentId,
            permission: it,
            idx: item.id + it,
          });
        });
      });
      this.defaultKeys = this.permissions.map((item) => item.idx);
      // console.log(this.permissions);
      // 权限选择器
      this.$http("/chongqing/stage/role/treeSelector", {}, "get", (res) => {
        if (res.data.code === 1000) {
          this.treeData = [];
          let list = res.data.data;
          list.map((item) => {
            let obj = item;
            if (obj.leaf.length > 0) {
              for (let i in obj.leaf) {
                if (obj.leaf[i].stringPermission) {
                  obj.leaf[i].label =
                    obj.leaf[i].menuName +
                    obj.leaf[i].stringPermission.slice(
                      obj.leaf[i].stringPermission.lastIndexOf(":"),
                      obj.leaf[i].stringPermission.length
                    );
                } else {
                  obj.leaf[i].label = obj.leaf[i].menuName;
                }
                obj.leaf[i].idx = obj.leaf[i].id + obj.leaf[i].stringPermission;
              }
            }
            if (obj.stringPermission) {
              obj.label =
                obj.menuName +
                obj.stringPermission.slice(
                  obj.stringPermission.lastIndexOf(":"),
                  obj.stringPermission.length
                );
            } else {
              obj.label = obj.menuName;
            }
            obj.idx = obj.id + obj.stringPermission;
            this.treeData.push(obj);
          });
          // console.log(this.treeData);
          this.jurisdictionModal = true; // 打开弹窗
        } else {
          this.$Message.error(res.data.msg);
        }
      });
    },
    submit2() {
      this.loading4 = true;
      // 查找重复元素
      let arrId = this.permissions.map((item) => item.id);
      const setter = new Set();
      const temp = new Set();
      for (const item of arrId) {
        if (setter.has(item)) {
          temp.add(item);
        } else {
          setter.add(item);
        }
      }
      // console.log(temp); // 有重复元素的id
      console.log(setter);
      let arr = Array.from(setter);
      let newArr = [];
      arr.map((it) => {
        let obj = {
          id: "",
          menuName: "",
          parentId: "",
          permission: "",
        };
        let arrP = [];
        this.permissions.map((item) => {
          if (item.id == it) {
            obj.id = item.id;
            obj.menuName = item.menuName;
            obj.parentId = item.parentId;
            arrP.push(item.permission);
          }
        });
        console.log(arrP);
        obj.permission = arrP.join(",");
        if (obj.permission) {
          newArr.push(obj);
        }
      });
      console.log(newArr);
      this.$http(
        "/chongqing/stage/role/updateRole",
        {
          id: this.menuId,
          permissions: newArr,
          organizationId: this.createData.organizationId,
          name: this.createData.name,
          remark: this.createData.remark,
        },
        "post",
        (res) => {
          if (res.data.code == 1000) {
            this.$Message.success("修改角色成功");
            this.getRoleData();
            this.jurisdictionModal = false;
          } else {
            this.$Message.error(res.data.msg);
          }
          this.loading4 = false;
        }
      );
    },
    // flatten(arr) {
    //   let renchong = deepClone(arr);
    //   for (let item of renchong) {
    //     if (item.children && item.children.length) {
    //       renchong = renchong.concat(this.flatten(item.children));
    //       delete item.children;
    //     }
    //   }
    //   return renchong;
    // },

    changePage(e) {
      this.current = e;
      this.getRoleData();
    },
    change() {
      this.current = 1;
      this.getRoleData();
    },

    // 双击查看提交内容
    onRowDblclick(data) {
      this.modalDetail = true;
      // this.$http(
      //   '/stage/museum/getMuseumSubmitMsg',
      //   {
      //     museumId: data.museumId
      //   },
      //   'get',
      //   (res) => {
      //     if (res.data.code == 200) {
      //       this.detailDataID = data.id
      //       this.detailData = res.data.data
      //       this.detailData.states = data.states
      //     } else {
      //       this.$Message.error(res.data.msg)
      //     }
      //   }
      // )
    },
  },
};
</script>

<style scoped>
.form >>> .el-tree-node {
  margin-bottom: 10px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.perView {
  width: 90%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
.perBox {
  margin-top: 20px;
  margin-right: 20px;
}
</style>
